<template>
	<a-select
		v-model:value="barnId"
		style="width: 100%"
		allow-clear
		placeholder="选择栏舍"
		:options="options"
		@change="handleChange"
		:disabled="barnDisable"
	></a-select>
</template>

<script setup="barnSelectByHenhouse">
	import BizBarnApi from "@/api/barn/bizBarnApi";

	const barnDisable = ref(true);
	const emit = defineEmits(['update:barnId', 'update:barnName']);
	const barnId = ref();
	const listData = ref([]);
	const options = ref([]);

	const selectByHenhouseId = (id) =>{
		const data = {
			henhouseId : id,
		}
		BizBarnApi.getListByHenhouseId(data)
			.then(resp =>{
				listData.value = resp;
				mapDataToOptions();
			})
			.catch(resp =>{
				console.log(resp);
			});
	};

	const mapDataToOptions = () => {
		options.value = listData.value.map(item => ({
			value: item.id,
			label: item.name,
		}));
	};

	const handleChange = (value) =>{
		if(value === undefined){
			emit('update:barnId', undefined);
			emit('update:barnName', undefined);
		}
		const selectedBarnId = value;
		const selectedBarn = listData.value.find(barn => barn.id === selectedBarnId);
		const selectedBarnName = selectedBarn ? selectedBarn.name : '';
		// 触发自定义事件
		if (selectedBarnId) {
			emit('update:barnId', selectedBarnId);
		}
		if (selectedBarnName) {
			emit('update:barnName', selectedBarnName);
		}
	}

	defineExpose({
		selectByHenhouseId,
		barnDisable,
		barnId,
	})
</script>

<style scoped>

</style>
